package com.xuetang9.t9.xinhuaxia.controller;

import com.github.pagehelper.PageInfo;
import com.xuetang9.t9.xinhuaxia.beans.ReceiveAddress;
import com.xuetang9.t9.xinhuaxia.beans.Token;
import com.xuetang9.t9.xinhuaxia.beans.User;
import com.xuetang9.t9.xinhuaxia.service.IReceiveAddressService;
import com.xuetang9.t9.xinhuaxia.service.IUserService;
import com.xuetang9.t9.xinhuaxia.service.IUserService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.List;
import java.util.UUID;

/**
 * @author 李亚奇
 * @version 1.0
 * @desc TODO
 * @date 2020/2/26 10:51
 * @copyright liyq
 * @address 成都西部国际金融中心2栋2201
 **/
@RestController
@RequestMapping("user")
public class UserController {
    @Autowired
    private IUserService userService;
    @Autowired
    private IReceiveAddressService receiveAddressService;
    @RequestMapping(value = "/save", method = RequestMethod.POST,produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String insertUser(HttpServletRequest request, MultipartFile file, String username, String password, String sex){
        System.out.println("新增用户");

        User user=new User();
        user.setuUsername(username);
        if(userService.queryByUserName(user)){
            return "userexist";
        }
        user.setuPassword(password);
        user.setuSex(sex);
        if (!file.isEmpty()) {
            try {
                // 文件保存路径
                String filePath = request.getSession().getServletContext().getRealPath("/backstage/userpicture/");
                File headimgfile =new File(filePath);
                if(!headimgfile.exists()){
                    headimgfile.mkdirs();
                }
                String filename=file.getOriginalFilename();
                String uuid= UUID.randomUUID().toString().replace("-","");
                filename=uuid+"-"+filename;
                // 转存文件
                file.transferTo(new File(filePath,filename));
                user.setuImgpath("/backstage/userpicture/"+filename);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        boolean insertUser = userService.insertUser(user);
        if(insertUser){
            return "success";
        }
        return "fail";
    }

    @GetMapping("remove/{id}")
    public boolean removeUser(@PathVariable(value = "id",required = false) Long id){
        boolean removeUser = userService.removeUser(id);
        return removeUser;
    }

    @GetMapping("queryById/{id}")
    public User queryById(@PathVariable(value = "id",required = false) Long id){
        User user = userService.queryById(id);
        return user;
    }
    @PostMapping("update")
    public boolean updateUser(@RequestBody User user){
        boolean updateUser = userService.updateUser(user);
        return updateUser;
    }
    @GetMapping("list/{page}/{perPagesize}")
    public PageInfo<User> queryByPage(@PathVariable(value = "page",required = false) Integer page,@PathVariable(value = "perPagesize",required = false) Integer perPagesize){
        PageInfo<User> pageInfo = userService.queryByPage(page, perPagesize);
        return pageInfo;
    }

    @RequestMapping("/login")
    public @ResponseBody Token login(@RequestBody User user,HttpServletRequest request){
        User loginuser=userService.login(user.getuUsername(),user.getuPassword());
        if(loginuser==null){
            return null;
        }
        String uuid= UUID.randomUUID().toString().replace("-","");
        Token  token=new Token(uuid,loginuser);
        HttpSession session = request.getSession();
        session.setAttribute("uuid","123");
        return  token;
    }

    @PostMapping("/isLogin")
    public void isLogin(@RequestHeader("Authorization") String token,HttpServletRequest request){
        System.out.println("社交登陆验证");
        HttpSession session = request.getSession();
    }



    @RequestMapping(value = "/insert",method = RequestMethod.POST,produces = "application/json;charset=UTF-8")
    public Boolean insertUserWithImages(HttpServletRequest request,User user){
        ServletContext servletContext = request.getServletContext();
        String realPath = servletContext.getRealPath("/");
        String savePath = realPath + "/backstage/userpicture";
        System.out.println(savePath);
        File saveFile = new File(savePath);
        if (!saveFile.exists()){
            saveFile.mkdir();
        }
        if (null != user.getUserHeaderPic()){
            String picPath = savePath + "/" + user.getUserHeaderPic().getOriginalFilename();
            System.out.println(picPath);
            File realFile = new File(picPath);
            try {
                Files.copy(user.getUserHeaderPic().getInputStream(),realFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
                String userheaderPath = "/backstage/userpicture/" + user.getUserHeaderPic().getOriginalFilename();
                user.setuImgpath(userheaderPath);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return userService.insertUser(user);
    }

    @RequestMapping("/queryaddress")
    public @ResponseBody List<ReceiveAddress> queryaddress(Long uid){
        ReceiveAddress receiveAddress =new ReceiveAddress();
        receiveAddress.setRaUserid(uid);
        return  receiveAddressService.queryByUid(receiveAddress);
    }

    @RequestMapping("/updateaddress")
    public String updateaddress(@RequestBody ReceiveAddress receiveAddress){
        if(receiveAddressService.updateReceiveAddress(receiveAddress)){
            return "updatesucess";
        }
        return  "updatefail";
    }

    @RequestMapping("/deleteaddress")
    public String deleteaddress(Long raAddressid){
          ReceiveAddress  receiveAddress=new ReceiveAddress();
        receiveAddress.setRaAddressid(raAddressid);
        if(receiveAddressService.removeReceiveAddress(receiveAddress)){
            return "deletesucess";
        }
        return  "deletefail";
    }

    @RequestMapping("/insertaddress")
    public String insertaddress(@RequestBody ReceiveAddress receiveAddress){
        if(receiveAddressService.insertReceiveAdress(receiveAddress)){
            return "insertsucess";
        }
        return  "insertfail";
    }
}
